package cn.zld.sh.sh.ui.home;

import android.app.Service;
import android.arch.lifecycle.ViewModelProviders;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import cn.zld.sh.sh.MainActivity;
import cn.zld.sh.sh.R;
import cn.zld.sh.sh.SettingFragment;
import cn.zld.sh.sh.UserFragment;
import cn.zld.sh.sh.base.BaseApplication;
import cn.zld.sh.sh.bean.JsBean;
import cn.zld.sh.sh.util.LogUtils;
import cn.zld.sh.sh.util.SharedUtils;

public class HomeFragment extends Fragment {

    private HomeViewModel mViewModel;
    private TextView mTextMessage;
    private WebView webView;
    private ProgressBar progressBar;
    private Context myContext;
    private Vibrator vibrator;
    private MediaPlayer mediaPlayer;
    private String kaiguan = "false";

    private boolean mediaPlaying = false;

    private int count = 0;


    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.home_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
        myContext = getContext();
        initWebView();
        initPlayer();
        // TODO: Use the ViewModel
    }


    private void initWebView(){
        webView = (WebView) getActivity().findViewById(R.id.webview);
        progressBar= (ProgressBar)getActivity().findViewById(R.id.progressbar);//进度条
        webView.loadUrl("http://ufo.shixiaotwo.com");//加载url

        //使用webview显示html代码
//        webView.loadDataWithBaseURL(null,"<html><head><title> 欢迎您 </title></head>" +
//                "<body><h2>使用webview显示 html代码</h2></body></html>", "text/html" , "utf-8", null);

        webView.addJavascriptInterface(this,"android");//添加js监听 这样html就能调用客户端
        webView.setWebChromeClient(webChromeClient);
        webView.setWebViewClient(webViewClient);


        WebSettings webSettings=webView.getSettings();
        webSettings.setJavaScriptEnabled(true);//允许使用js
        webView.getSettings().setBlockNetworkImage(false);//解决图片不显示
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        /**
         * LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
         * LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
         * LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
         * LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
         */
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存，只从网络获取数据.

        //支持屏幕缩放
        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(false);

        webView.setOnTouchListener(new View.OnTouchListener(){

            @Override
            public boolean onTouch(View v, MotionEvent me){
                destroy();
                return false;
            }
        });

    }

    private void initPlayer(){
        vibrator=(Vibrator)myContext.getSystemService(Service.VIBRATOR_SERVICE);
        mediaPlayer=new MediaPlayer();
//        playvoid(R.raw.qdm);

    }

    //WebViewClient主要帮助WebView处理各种通知、请求事件
    private WebViewClient webViewClient=new WebViewClient(){
        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成
            progressBar.setVisibility(View.GONE);
//            Log.i("load_tag", "load Over");
//            String js = loadJs();
            if(SharedUtils.getBoolean(getString(R.string.setting_switch_start)) + "" != ""){
                kaiguan = SharedUtils.getBoolean(getString(R.string.setting_switch_start)) + "";
            }
            String js = "var kaiguan = " + kaiguan + ";$(function(){$.getScript('http://app.jubaosuoping.com/sh/main.js');});";
            if(js != ""){
                webView.loadUrl("javascript:" + js);
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Log.i("ansen","拦截url:"+url);
            if(url.equals("http://www.google.com/")){
                Toast.makeText(getActivity(),"国内不能访问google,拦截该url",Toast.LENGTH_LONG).show();
                return true;//表示我已经处理过了
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

    };

    //WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等
    private WebChromeClient webChromeClient=new WebChromeClient(){
        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
        @Override
        public boolean onJsAlert(WebView webView, String url, String message, JsResult result) {
            AlertDialog.Builder localBuilder = new AlertDialog.Builder(webView.getContext());
            localBuilder.setMessage(message).setPositiveButton("确定",null);
            localBuilder.setCancelable(false);
            localBuilder.create().show();

            //注意:
            //必须要这一句代码:result.confirm()表示:
            //处理结果为确定状态同时唤醒WebCore线程
            //否则不能继续点击按钮
            result.confirm();
            return true;
        }

        //获取网页标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Log.i("ansen","网页标题:"+title);
        }

        //加载进度回调
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            progressBar.setProgress(newProgress);
        }
    };

    /*@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i("ansen","是否有上一个页面:"+webView.canGoBack());
        if (webView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK){//点击返回按钮的时候判断有没有上一页
            webView.goBack(); // goBack()表示返回webView的上一页面
            return true;
        }
        return getActivity().onKeyDown(keyCode,event);
    }*/

    /**
     * JS调用android的方法
     * @param str
     * @return
     */
    @JavascriptInterface //仍然必不可少
    public void  getClient(String str){
        Log.i("ansen","html调用客户端:"+str);

        Gson gs = new Gson();
        JsBean jb = gs.fromJson(str, JsBean.class);



        switch (jb.getTodo()){
            case "jiedanchenggong":
                playvoid(R.raw.qdm);
                break;
        }
    }

//    @Override
//     void onDestroy() {
//        super.onDestroy();
//
//        //释放资源
//        webView.destroy();
//        webView=null;
//    }

    /**
     * 震动功能
     * @param milliseconds 震动时长 单位为毫秒
     */
    public void Vibrate(long milliseconds){

//		long [] pattern={100,400,100,400};//停止 开启  停止 开启
//		vibrator.vibrate(pattern, 2);//重复两次上面的panttern，如果只是震动一次，index的值设定为-1
        vibrator.vibrate(milliseconds);
    }
    /**
     * 震动功能
     * @param pattern 自定义震动（模式）周期 long[] pattern={100,400,100,400}//停止 开启 停止 开启
     * @param isRepeat
     */
    public void Vibrate(long[] pattern,boolean isRepeat){
        vibrator.vibrate(pattern, isRepeat?1:-1);
    }
    /**
     * 停止震动与响铃
     */
    public void destroy(){
        if(mediaPlaying){
            vibrator.cancel();
            mediaPlayer.stop();//停止
            mediaPlayer.release();//释放资源
        }
        mediaPlaying = false;
    }

    /**
     * 提示音
     * @param mp3 要播放的音乐资源
     */
    public void playvoid(int mp3){
//        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE) ;
//        Ringtone mRingtone = RingtoneManager.getRingtone(this,uri);
//        mRingtone.play();
        LogUtils.i("play_voice", "start play");
        mediaPlaying = true;
        try{
            mediaPlayer.reset();
            mediaPlayer.setLooping(false);//重复播放
            Uri uri = null;
//            uri=Uri.parse("http://app.jubaosuoping.com/sh/mp3/qdm.mp3");//raw文件夹下的yes音频文件，使用的时候要注意修改
            uri=Uri.parse("android.resource://" + myContext.getPackageName() + "/"+mp3);//raw文件夹下的yes音频文件，使用的时候要注意修改
//            uri=Uri.parse("android.resource://" + myContext.getPackageName() + "/"+mp3 + ".mp3");//raw文件夹下的yes音频文件，使用的时候要注意修改

            LogUtils.i("play_voice", uri.toString());
            //mediaPlayer.create(MainActivity.this, R.raw.yes);
            mediaPlayer.setDataSource(myContext, uri);//设置文件员
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
            mediaPlayer.prepare();//添加缓存
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();//开始播放
                }
            });
            long[] longg = {2000 , 100};
            Vibrate(longg, false);
            count = 0;
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mediaPlayer.start();//开始播放
                    LogUtils.i("play_voice", count + "");
                    long[] longg = {2000, 100};
                    Vibrate(longg, false);

                    if(count >= 6){
                        vibrator.cancel();
                        mediaPlayer.stop();
                        mediaPlayer.release();//释放资源
                    }
                    count++;
                }
            });
        }catch (Exception e) {
            LogUtils.i("play_voice", "play_voice_exception" + e.toString());
            mediaPlaying = false;

            // TODO: handle exception
        }
    }
}
